package LC;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * https://leetcode.com/problems/subsets/description/
 * Given a set of distinct integers, nums, return all possible subsets.
 * Note: The solution set must not contain duplicate subsets.
 * For example,
 * If nums = [1,2,3], a solution is:
 * [
 * [3],
 * [1],
 * [2],
 * [1,2,3],
 * [1,3],
 * [2,3],
 * [1,2],
 * []
 * ]
 */
public class LC_078_Subsets_DFS_BackTracking {
    public static void main(String[] args) {
        System.out.println(Solution.subsets(new int[]{1, 2, 3}).toString());
        System.out.println(Solution_1.subsets(new int[]{1, 2, 3}).toString());
    }

    static class Solution {
        static List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> res = new LinkedList<>();
            List<Integer> tmpList = new LinkedList<>();
            Arrays.sort(nums);
            dfs(res, nums, tmpList, 0);
            return res;
        }

        private static void dfs(List<List<Integer>> res, int[] nums, List<Integer> item, int index) {
            if (index == nums.length) {
                res.add(new ArrayList<>(item));
                return;
            }
            dfs(res, nums, item, index + 1);
            item.add(nums[index]);
            dfs(res, nums, item, index + 1);
            item.remove(item.size() - 1);
        }
    }

    static class Solution_1 {
        static List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> result = new LinkedList<>();
            Arrays.sort(nums);
            process(0, nums, result, new LinkedList<>());
            return result;
        }

        private static void process(int index, int[] nums, List<List<Integer>> result, List<Integer> item) {
            result.add(new LinkedList<>(item));
            for (int i = index; i < nums.length; i++) {
                item.add(nums[i]);
                process(i + 1, nums, result, item);
                item.remove(item.size() - 1);
            }
        }
    }
}
